package com.cat.controller;

import com.cat.constant.JwtClaimsConstant;
import com.cat.context.BaseContext;
import com.cat.entity.Employee;
import com.cat.entity.LoginInfo;
import com.cat.properties.JwtProperties;
import com.cat.result.Result;
import com.cat.service.EmployeeService;
import com.cat.vo.LoginVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import com.cat.utils.JwtUtil;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping
@Slf4j
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
@Tag(name = "登录")
public class LoginController {

    private final EmployeeService employeeService;
    private final JwtProperties jwtProperties;

    @PostMapping("/auth/login")
    @Operation(summary = "登录")
    public Result<LoginVO> login(@RequestBody LoginInfo loginInfo) {
        log.info("登录信息：{}:", loginInfo);

        Employee employee = employeeService.login(loginInfo);

//        String[] split = employee.getRoles().split(",");

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        LoginVO loginVO = LoginVO.builder()
                .access_token(token)
//                .id(employee.getId())
////                .password(employee.getPwd())
//                .username(employee.getUsername())
//                .roles(split)
                .build();
        return Result.success(loginVO,"成功");
    }

    @PostMapping("/logout")
    @Operation(summary = "退出登录")
    public Result<String> logout(){
        log.info("退出登录用户ID：{}",BaseContext.getCurrentId());

        return Result.success("成功");
    }

//    @GetMapping("/codes")
//    @Operation(summary = "获取用户可操作权限")
//    public Result<String[]> codes(){
//        Employee employee = employeeService.getById(BaseContext.getCurrentId());
//        String[] split = employee.getButtons().split(",");
//        return Result.success(split,"ok");
//    }

}
